package com.ymatou.operate.trading.api.testcase;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.json.JSONArray;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.ymatou.operate.trading.api.parameter.BatchApplyForPostPayBean;
import com.ymatou.operate.trading.api.parameter.PlaceOrderBean;
import com.ymatou.operate.trading.api.service.BatchApplyForPostPayCall;
import com.ymatou.operate.trading.api.service.PlaceOrderCall;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.TestCase;
import com.ymt.utils.annotation.TestSuite;
import com.ymt.utils.tag.P1;
import com.ymt.utils.tag.P3;
import com.ymttest.business.service.CouponCallService;
import com.ymttest.business.service.OrderCallService;
import com.ymttest.business.service.ProductCallService;
import com.ymttest.common.entitie.ApplyPostPayInfo;
import com.ymttest.common.entitie.OrderInfo;
import com.ymttest.common.entitie.OrderProductInfo;
import com.ymttest.common.entitie.ProductActivityInfo;
import com.ymttest.common.enums.ActivityPromotionTypeEnum;
import com.ymttest.common.enums.AppTerminalSourceEnum;
import com.ymttest.common.enums.BondedAreaEnum;
import com.ymttest.common.enums.LogisticsTypeEnum;
import com.ymttest.common.enums.OrderSourceEnum;
import com.ymttest.common.enums.OrderTypeEnum;
import com.ymttest.common.enums.PriceTypeEnum;
import com.ymttest.common.enums.ProductRefundChannelEnum;
import com.ymttest.common.enums.StockStatusEnum;
import com.ymttest.common.enums.TerminalSourceEnum;
import com.ymttest.database.sqlwapper.DefaultWapper;
import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.TestDataManager;
import com.ymttest.utils.YMTDateUtil;
import com.ymttest.utils.constant.ECode;

/**
 * 批量申请补款接口 FreeMaker Template自动生成代码
 */
@TestSuite
public class Ts_BatchApplyForPostPay {
    private static BatchApplyForPostPayBean bafppbean;
    private static BatchApplyForPostPayCall bafppcall;

    @BeforeClass
    public static void setUp() {
        Logger.createResultFile("批量申请补款接口");
    }

    @Before
    public void caseUp() {
        bafppbean = new BatchApplyForPostPayBean();
        bafppcall = new BatchApplyForPostPayCall();
    }

    @AfterClass
    public static void tearDown() {
        Logger.generateResult(bafppcall.getOpurl());
    }

    @After
    public void caseDown() {
        Logger.end();
    }

    // 数据库验证
    private void verifyDb(int userId) {
        // 数据库验证
        DefaultWapper database = new DefaultWapper();
        int size = bafppbean.getApplyPostPayInfoList().size();

        for (int i = 0; i < size; i++) {
            int orderId = bafppbean.getApplyPostPayInfoList().get(i).getOrderId();
            HashMap m = new HashMap();
            m.put("OrderId", orderId);
            m.put("TradingStatus", 16);
            m.put("UserId", userId);
            m.put("TraddingId", orderId);
            Logger.verifyEquals(size, bafppcall.getSuccessNum(), "验证批量补款记录条数");
            Logger.verifyEquals(1, database.selectOrder(m).size(), "验证订单表记录");
            Logger.verifyEquals(1, database.selectTradingStatus(m).size(), "验证交易表记录");
            Logger.verifyEquals(1, database.selectOrderPostPayByOrderId(orderId).size(), "验证补款记录表");
            Logger.verifyEquals(orderId, bafppcall.getPostPayResultList().get(i).getOrderId(), "验证返回结果OrderId");
            Logger.verifyEquals((String) database.selectOrderPostPayByOrderId(orderId).get(0).get("sId"), bafppcall
                    .getPostPayResultList().get(i).getPostPayId(), "验证返回结果PostPayId");
            Logger.verifyEquals(true, bafppcall
                    .getPostPayResultList().get(i).getIsSuccess(), "验证返回结果PostPayId");
        }
    }

    @Test
    @Category(P1.class)
    @TestCase
    public void Tc_BatchApplyForPostPay_001() {
        Logger.start(true, "批量申请补款成功");
        try {
            // 循环两次，增加两条补款记录
            Logger.comment("前置数据准备");
            int userId = 0;
            ArrayList<ApplyPostPayInfo> list = new ArrayList<ApplyPostPayInfo>();
            for (int i = 0; i < 2; i++) {
                // 创建订单
                Map map = new OrderCallService().appSaveOrder();
                int orderId = (Integer) map.get("orderId");
                int sellerId = (Integer) map.get("sellerId");
                userId = (Integer) map.get("userId");
                int tradingId = (Integer) map.get("tradingId");
                DecimalFormat df = new DecimalFormat("0.00");// 保留两位小数
                BigDecimal totalPrice = (BigDecimal) map.get("totalPrice");// 金额
                /** 买家付定金 **/
                new OrderCallService().orderPayRequest(userId, totalPrice, tradingId);
                // 接单
                new OrderCallService().acceptOrder(orderId, sellerId);
                // 补款参数
                ApplyPostPayInfo info = new ApplyPostPayInfo();
                // 补款理由
                info.setApplyReason("自动化测试");
                // 订单ID
                info.setOrderId(orderId);
                // 支付金额
                BigDecimal PayAmount = new BigDecimal(10);
                info.setPostPayAmount(PayAmount);
                // 补款类型
                info.setPostPayType(2);
                // 买家ID
                info.setSellerId(sellerId);
                list.add(info);
            }
            Logger.comment("前置数据准备结束");
            bafppbean.setApplyPostPayInfoList(list);
            // 发送请求
            bafppcall.setData(bafppbean);
            bafppcall.callService();
            Logger.verifyEquals(ECode.SUCCESS, bafppcall.getCode(), "验证Code");
            Logger.verifyEquals(true, bafppcall.getPostPayResultList().get(0).getIsSuccess(), "验证第一条补款是否成功");
            Logger.verifyEquals(true, bafppcall.getPostPayResultList().get(1).getIsSuccess(), "验证第二条补款是否成功");
            // 数据库验证
            verifyDb(userId);
        } catch (Exception e) {
            Logger.fail(e);
        }
    }

    @Test
    @Category(P3.class)
    @TestCase
    public void Tc_BatchApplyForPostPay_002() {
        Logger.start(true, "订单不存在，批量申请补款失败");
        try {
            Logger.comment("前置数据准备");
            // 循环两次，增加两条补款记录
            ArrayList<ApplyPostPayInfo> list = new ArrayList<ApplyPostPayInfo>();
            for (int i = 0; i < 2; i++) {
                // 补款参数
                ApplyPostPayInfo info = new ApplyPostPayInfo();
                // 补款理由
                info.setApplyReason("自动化测试");
                // 订单ID
                info.setOrderId(123);
                // 支付金额
                BigDecimal PayAmount = new BigDecimal(10);
                info.setPostPayAmount(PayAmount);
                // 补款类型
                info.setPostPayType(2);
                // 买家ID
                info.setSellerId(288484);
                list.add(info);
            }
            Logger.comment("前置数据准备结束");
            bafppbean.setApplyPostPayInfoList(list);
            // 发送请求
            bafppcall.setData(bafppbean);
            bafppcall.callService();
            Logger.verifyEquals(ECode.SUCCESS, bafppcall.getCode(), "验证Code");
            Logger.verifyEquals(false, bafppcall.getPostPayResultList().get(0).getIsSuccess(), "验证第一条补款是否不成功");
            Logger.verifyEquals(true,
                    bafppcall.getPostPayResultList().get(0).getPostPayId().contains(ECode.FAILED201_MSG_11), "验证信息:"
                            + bafppcall.getPostPayResultList().get(0).getPostPayId());
            Logger.verifyEquals(false, bafppcall.getPostPayResultList().get(1).getIsSuccess(), "验证第二条补款是否不成功");
            Logger.verifyEquals(true,
                    bafppcall.getPostPayResultList().get(1).getPostPayId().contains(ECode.FAILED201_MSG_11), "验证信息:"
                            + bafppcall.getPostPayResultList().get(1).getPostPayId());

        } catch (Exception e) {
            Logger.fail(e);
        }
    }

    @Test
    @Category(P3.class)
    @TestCase
    public void Tc_BatchApplyForPostPay_003() {
        Logger.start(true, "当前状态不能申请补款");
        try {
            // 循环两次，增加两条补款记录
            Logger.comment("前置数据准备");
            int userId = 0;
            ArrayList<ApplyPostPayInfo> list = new ArrayList<ApplyPostPayInfo>();
            for (int i = 0; i < 2; i++) {
                // 创建订单
                Map map = new OrderCallService().appSaveOrder();
                int orderId = (Integer) map.get("orderId");
                int sellerId = (Integer) map.get("sellerId");
                userId = (Integer) map.get("userId");
                int tradingId = (Integer) map.get("tradingId");
                DecimalFormat df = new DecimalFormat("0.00");// 保留两位小数
                BigDecimal totalPrice = (BigDecimal) map.get("totalPrice");// 金额
                /** 买家付定金 **/
                new OrderCallService().orderPayRequest(userId, totalPrice, tradingId);
                // 接单
                // new OrderCallService().acceptOrder(OrderId, SellerId);
                // 补款参数
                ApplyPostPayInfo info = new ApplyPostPayInfo();
                // 补款理由
                info.setApplyReason("自动化测试");
                // 订单ID
                info.setOrderId(orderId);
                // 支付金额
                BigDecimal PayAmount = new BigDecimal(10);
                info.setPostPayAmount(PayAmount);
                // 补款类型
                info.setPostPayType(2);
                // 买家ID
                info.setSellerId(sellerId);
                list.add(info);
            }
            Logger.comment("前置数据准备结束");
            bafppbean.setApplyPostPayInfoList(list);
            // 发送请求
            bafppcall.setData(bafppbean);
            bafppcall.callService();
            Logger.verifyEquals(ECode.SUCCESS, bafppcall.getCode(), "验证Code");
            Logger.verifyEquals(true,
                    bafppcall.getPostPayResultList().get(0).getPostPayId().contains(ECode.FAILED201_MSG_47), "验证Msg:"
                            + bafppcall.getPostPayResultList().get(0).getPostPayId());
        } catch (Exception e) {
            Logger.fail(e);
        }
    }

    @Test
    @Category(P3.class)
    @TestCase
    public void Tc_BatchApplyForPostPay_004() {
        Logger.start(true, "重复申请补款");
        try {
            // 循环两次，增加两条补款记录
            Logger.comment("前置数据准备");
            int userId = 0;
            ArrayList<ApplyPostPayInfo> list = new ArrayList<ApplyPostPayInfo>();
            for (int i = 0; i < 2; i++) {
                // 创建订单
                Map map = new OrderCallService().appSaveOrder();
                int orderId = (Integer) map.get("orderId");
                int sellerId = (Integer) map.get("sellerId");
                userId = (Integer) map.get("userId");
                int tradingId = (Integer) map.get("tradingId");
                DecimalFormat df = new DecimalFormat("0.00");// 保留两位小数
                BigDecimal totalPrice = (BigDecimal) map.get("totalPrice");// 金额
                /** 买家付定金 **/
                new OrderCallService().orderPayRequest(userId, totalPrice, tradingId);
                // 接单
                new OrderCallService().acceptOrder(orderId, sellerId);
                // 卖家申请补款
                BigDecimal PayAmount = new BigDecimal(10);
                new OrderCallService().applyForPostPay(orderId, sellerId, PayAmount);
                // 补款参数
                ApplyPostPayInfo info = new ApplyPostPayInfo();
                // 补款理由
                info.setApplyReason("自动化测试");
                // 订单ID
                info.setOrderId(orderId);
                // 支付金额
                info.setPostPayAmount(PayAmount);
                // 补款类型
                info.setPostPayType(2);
                // 买家ID
                info.setSellerId(sellerId);
                list.add(info);
            }
            Logger.comment("前置数据准备结束");
            bafppbean.setApplyPostPayInfoList(list);
            // 发送请求
            bafppcall.setData(bafppbean);
            bafppcall.callService();
            Logger.verifyEquals(ECode.SUCCESS, bafppcall.getCode(), "验证Code");
            // 数据库验证
            verifyDb(userId);
        } catch (Exception e) {
            Logger.fail(e);
        }
    }

    @Test
    @Category(P3.class)
    @TestCase
    public void Tc_BatchApplyForPostPay_005() {
        Logger.start(true, "订单退货退款中,批量补款失败");
        try {
            // 循环两次，增加两条补款记录
            Logger.comment("前置数据准备");
            int userId = 0;
            ArrayList<ApplyPostPayInfo> list = new ArrayList<ApplyPostPayInfo>();
            for (int i = 0; i < 2; i++) {
                // 创建订单
                Map map = new OrderCallService().appSaveOrder();
                int orderId = (Integer) map.get("orderId");
                int sellerId = (Integer) map.get("sellerId");
                userId = (Integer) map.get("userId");
                int tradingId = (Integer) map.get("tradingId");
                DecimalFormat df = new DecimalFormat("0.00");// 保留两位小数
                BigDecimal totalPrice = (BigDecimal) map.get("totalPrice");// 金额
                /** 买家付定金 **/
                new OrderCallService().orderPayRequest(userId, totalPrice, tradingId);
                // 接单
                new OrderCallService().acceptOrder(orderId, sellerId);
                // 退货退款同步中
                new OrderCallService().applySalesRefundRequestInJava(orderId);
                // 补款参数
                ApplyPostPayInfo info = new ApplyPostPayInfo();
                // 补款理由
                info.setApplyReason("自动化测试");
                // 订单ID
                info.setOrderId(orderId);
                // 支付金额
                BigDecimal PayAmount = new BigDecimal(10);
                info.setPostPayAmount(PayAmount);
                // 补款类型
                info.setPostPayType(2);
                // 买家ID
                info.setSellerId(sellerId);
                list.add(info);
            }
            Logger.comment("前置数据准备结束");
            bafppbean.setApplyPostPayInfoList(list);
            // 发送请求
            bafppcall.setData(bafppbean);
            bafppcall.callService();
            Logger.verifyEquals(ECode.SUCCESS, bafppcall.getCode(), "验证Code");
            Logger.verifyEquals(false, bafppcall.getPostPayResultList().get(0).getIsSuccess(), "验证第一条补款是否成功");
            Logger.verifyEquals(ECode.FAILED201_MSG_62, bafppcall.getPostPayResultList().get(0).getPostPayId(),
                    "验证第一条补款是否成功");
            Logger.verifyEquals(false, bafppcall.getPostPayResultList().get(1).getIsSuccess(), "验证第二条补款是否成功");
            Logger.verifyEquals(ECode.FAILED201_MSG_62, bafppcall.getPostPayResultList().get(1).getPostPayId(),
                    "验证第一条补款是否成功");
            Logger.verifyEquals(0, bafppcall.getSuccessNum(), "验证批量补款记录条数");
            // 数据库验证
            DefaultWapper database = new DefaultWapper();
            Thread.sleep(500);
            for (int i = 0; i < list.size(); i++) {
                int OrderId = list.get(i).getOrderId();
                HashMap m = new HashMap();
                m.put("OrderId", OrderId);
                m.put("TradingStatus", 16);
                m.put("UserId", userId);
                m.put("TraddingId", OrderId);
                Logger.verifyEquals(0, database.selectOrder(m).size(), "验证订单表记录");
                Logger.verifyEquals(0, database.selectOrderPostPayByOrderId(OrderId).size(), "验证补款记录表");
                Logger.verifyEquals(0, database.selectTradingStatus(m).size(), "验证交易表记录");
            }
        } catch (Exception e) {
            Logger.fail(e);
        }
    }

    @Test
    @Category(P1.class)
    @TestCase
    public void Tc_BatchApplyForPostPay_006() {
        Logger.start(true, "操作用户不是订单所有者,批量补款成功");
        try {
            // 循环两次，增加两条补款记录
            Logger.comment("前置数据准备");
            int userId = 0;
            ArrayList<ApplyPostPayInfo> list = new ArrayList<ApplyPostPayInfo>();
            for (int i = 0; i < 2; i++) {
                // 创建订单
                Map map = new OrderCallService().appSaveOrder();
                int orderId = (Integer) map.get("orderId");
                int sellerId = (Integer) map.get("sellerId");
                userId = (Integer) map.get("userId");
                int tradingId = (Integer) map.get("tradingId");
                DecimalFormat df = new DecimalFormat("0.00");// 保留两位小数
                BigDecimal totalPrice = (BigDecimal) map.get("totalPrice");// 金额
                /** 买家付定金 **/
                new OrderCallService().orderPayRequest(userId, totalPrice, tradingId);
                // 接单
                new OrderCallService().acceptOrder(orderId, sellerId);
                // 补款参数
                ApplyPostPayInfo info = new ApplyPostPayInfo();
                // 补款理由
                info.setApplyReason("自动化测试");
                // 订单ID
                info.setOrderId(orderId);
                // 支付金额
                BigDecimal PayAmount = new BigDecimal(10);
                info.setPostPayAmount(PayAmount);
                // 补款类型
                info.setPostPayType(2);
                // 买家ID
                info.setSellerId(2222);
                list.add(info);
            }
            Logger.comment("前置数据准备结束");
            bafppbean.setApplyPostPayInfoList(list);
            // 发送请求
            bafppcall.setData(bafppbean);
            bafppcall.callService();
            Logger.verifyEquals(ECode.SUCCESS, bafppcall.getCode(), "验证Code");
            Logger.verifyEquals(true, bafppcall.getPostPayResultList().get(0).getIsSuccess(), "验证第一条补款是否成功");
            Logger.verifyEquals(true, bafppcall.getPostPayResultList().get(1).getIsSuccess(), "验证第二条补款是否成功");
            Logger.verifyEquals(2, bafppcall.getSuccessNum(), "验证批量补款记录条数");
            // 数据库验证
            verifyDb(userId);
        } catch (Exception e) {
            Logger.fail(e);
        }
    }

    @Test
    @Category(P1.class)
    @TestCase
    public void Tc_BatchApplyForPostPay_007() {
        Logger.start(true, "批量申请2单补款,其中一单补款金额大于实际补款，另一单小于实际补款金额");
        try {
            // 循环两次，增加两条补款记录
            Logger.comment("前置数据准备");
            int userId = Integer.valueOf(EnvSetup.getData("BuyUserId"));
            int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));
            ArrayList<ApplyPostPayInfo> list = new ArrayList<ApplyPostPayInfo>();
            OrderCallService orderService = new OrderCallService();
            DefaultWapper database = new DefaultWapper();
            Map map = placeOrder();
            JSONArray orders = (JSONArray) map.get("orders");
            int tradingId = (Integer) map.get("tradingId");
            // 订单1
            int orderId1 = orders.getInt(0);
            // 订单2
            int orderId2 = orders.getInt(1);
            // 获取用户需要支付的金额
            // ymt_tradinginfo 表
            List<Map> ymtTradinginfo = database.selectTradinginfoByTradingId(tradingId);
            BigDecimal needPayAmount = (BigDecimal) ymtTradinginfo.get(0).get("fPayableAmount");
            // 订单主表
            List<Map> ymtOrders = database.selectOrderByOderId(orderId1);
            // 调整金额
            BigDecimal discount = (BigDecimal) ymtOrders.get(0).get("fDiscount");
            // 总付款金额
            BigDecimal totalPrice = (BigDecimal) ymtOrders.get(0).get("fTotalPrice");
            // 定金金额
            BigDecimal orderPrice = (BigDecimal) ymtOrders.get(0).get("fOrderPrice");
            // 实际需要补款金额
            BigDecimal needPostPayPrice = totalPrice.subtract(orderPrice);
            // 订单主表 2
            List<Map> ymtOrders2 = database.selectOrderByOderId(orderId2);
            // 调整金额
            BigDecimal discount2 = (BigDecimal) ymtOrders2.get(0).get("fDiscount");
            // 总付款金额
            BigDecimal totalPrice2 = (BigDecimal) ymtOrders2.get(0).get("fTotalPrice");
            // 定金金额
            BigDecimal orderPrice2 = (BigDecimal) ymtOrders2.get(0).get("fOrderPrice");
            // 实际需要补款金额
            BigDecimal needPostPayPrice2 = totalPrice2.subtract(orderPrice2);
            /** 买家付定金 **/
            orderService.orderPayRequest(userId, needPayAmount, tradingId);

            // 接单
            orderService.acceptOrder(orderId1, sellerId);
            // 接单2
            orderService.acceptOrder(orderId2, sellerId);

            // 补款参数
            ApplyPostPayInfo info = new ApplyPostPayInfo();
            // 补款理由
            info.setApplyReason("自动化测试");
            // 订单ID
            info.setOrderId(orderId1);
            // 支付金额
            BigDecimal PayAmount = needPostPayPrice.add(new BigDecimal(21));
            info.setPostPayAmount(PayAmount);
            // 补款类型
            info.setPostPayType(2);
            // 买家ID
            info.setSellerId(sellerId);

            // 补款参数
            ApplyPostPayInfo info2 = new ApplyPostPayInfo();
            // 补款理由
            info2.setApplyReason("自动化测试");
            // 订单ID
            info2.setOrderId(orderId2);
            // 支付金额
            BigDecimal PayAmount2 = needPostPayPrice2.subtract(new BigDecimal(11));
            info2.setPostPayAmount(PayAmount2);
            // 补款类型
            info2.setPostPayType(2);
            // 买家ID
            info2.setSellerId(sellerId);

            list.add(info);
            list.add(info2);

            Logger.comment("前置数据准备结束");
            bafppbean.setApplyPostPayInfoList(list);
            // 发送请求
            bafppcall.setData(bafppbean);
            bafppcall.callService();
            Logger.verifyEquals(ECode.SUCCESS, bafppcall.getCode(), "验证Code");
            Logger.verifyEquals(true, bafppcall.getPostPayResultList().get(0).getIsSuccess(), "验证第一条补款是否成功");
            Logger.verifyEquals(true, bafppcall.getPostPayResultList().get(1).getIsSuccess(), "验证第二条补款是否成功");
            Logger.verifyEquals(2, bafppcall.getSuccessNum(), "验证批量补款记录条数");
            // 数据库验证
            verifyDb(userId);
            // 校验订单下商品调整金额分摊
            verifyDb2(orderId1, PayAmount);
            verifyDb2(orderId2, PayAmount2);
        } catch (Exception e) {
            Logger.fail(e);
        }
    }

    private void verifyDb2(int orderId, BigDecimal postPayAmount) {
        DefaultWapper database = new DefaultWapper();
        // 订单主表
        List<Map> ymtOrders = database.selectOrderByOderId(orderId);
        // 订单商品明细
        List<Map> ymtOrdersInfoList = database.selectOrderInfoByOderId(orderId);
        // 调整金额
        BigDecimal discount = (BigDecimal) ymtOrders.get(0).get("fDiscount");
        // 总付款金额
        BigDecimal totalPrice = (BigDecimal) ymtOrders.get(0).get("fTotalPrice");

        // 运费
        BigDecimal freight = (BigDecimal) ymtOrders.get(0).get("fFreight");
        // 商家优惠券
        BigDecimal fSellerCouponAmount = (BigDecimal) ymtOrders.get(0).get("fSellerCouponAmount");
        // 平台优惠券
        BigDecimal fYmtCouponAmount = (BigDecimal) ymtOrders.get(0).get("fYmtCouponAmount");
        // 定金金额
        BigDecimal orderPrice = (BigDecimal) ymtOrders.get(0).get("fOrderPrice");
        // 申请补款金额
        BigDecimal applyPostorderPrice = postPayAmount;
        // 实际应该补款金额
        BigDecimal needPostPayPrice = totalPrice.subtract(orderPrice);
        Logger.verifyEquals(
                BigDecimal.ZERO.setScale(2)
                ,
                (BigDecimal) ymtOrders.get(0).get("fDiscount"),
                "验证fDiscount");
        BigDecimal newPayableAmount =
                totalPrice.add(freight).add(applyPostorderPrice.subtract(needPostPayPrice))
                        .subtract(fSellerCouponAmount).subtract(fYmtCouponAmount);
        // 应付金额调整
        Logger.verifyEquals(
                newPayableAmount,
                (BigDecimal) ymtOrders.get(0).get("fPayableAmount"),
                "验证fPayableAmount");


        BigDecimal tempDicount = new BigDecimal(0);
        for (int i = 0; i < ymtOrdersInfoList.size(); i++) {
            // 订单商品信息表
            Map orderInfoMap = ymtOrdersInfoList.get(i);
            BigDecimal productPrice = (BigDecimal) orderInfoMap.get("fProductPrice");
            int proNum = (Integer) orderInfoMap.get("iAmount");
            if (!(new BigDecimal(0).divide(new BigDecimal(1), 2)).equals(discount)) {
                BigDecimal rate = productPrice.multiply(new BigDecimal(proNum))
                        .divide(totalPrice, 5, BigDecimal.ROUND_HALF_DOWN);
                BigDecimal productDiscount = new BigDecimal(0);

                if (i == ymtOrdersInfoList.size() - 1) {
                    productDiscount = discount.subtract(tempDicount);
                }
                else {
                    // 商品里的调整分摊金额
                    productDiscount =
                            discount.multiply(rate).divide(new BigDecimal(1), 2, BigDecimal.ROUND_HALF_UP);
                }
                tempDicount = tempDicount.add(productDiscount);
                Logger.verifyEquals(
                        productDiscount,
                        (BigDecimal) orderInfoMap.get("fDiscount"),
                        "验证fDiscount");
            }
            else {
                Logger.verifyEquals(
                        new BigDecimal(0).divide(new BigDecimal(1), 2, 4),
                        (BigDecimal) orderInfoMap.get("fDiscount"),
                        "验证fDiscount");
            }
        }

    }

    // 一次下单生成2个订单号,分别使用平台,商家优惠券,每个订单下面3个商品
    private Map placeOrder() {
        Map map = new HashMap();
        try {
            PlaceOrderBean placeorderBean = new PlaceOrderBean();
            PlaceOrderCall placeorderCall = new PlaceOrderCall();
            int userId = Integer.valueOf(EnvSetup.getData("BuyUserId"));
            int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));
            // 创建产品
            Logger.comment("前置数据准备");
            HashMap<String, Object> productInfo = ProductCallService.createProduct(sellerId, 3);
            Logger.comment("前置数据准备结束");
            String productId = (String) productInfo.get("productId");
            Logger.debug("productId:" + productId);
            String productName = (String) productInfo.get("productName");
            String pic = (String) productInfo.get("pic");
            BigDecimal price = (BigDecimal) (productInfo.get("price"));
            // String catalogId = (String) productInfo.get("catalogId");
            // 买家用户等级
            int userLevel = 3;
            // 订单来源
            int orderSource = OrderSourceEnum.APP.getValue();
            placeorderBean.setOrderSource(orderSource);
            // 终端来源
            int terminalSource = TerminalSourceEnum.IOS.getValue();
            placeorderBean.setTerminalSource(terminalSource);
            // 应用终端来源
            int appTerminalSource = AppTerminalSourceEnum.Phone.getValue();
            placeorderBean.setAppTerminalSource(appTerminalSource);
            // SourceIp
            String sourceIp = "127.0.0.1";
            placeorderBean.setSourceIp(sourceIp);
            // 用户设备号
            String deviceId = "";
            placeorderBean.setDeviceId(deviceId);
            // 订单信息List
            List<OrderInfo> orderInfoList = new ArrayList<OrderInfo>();
            OrderInfo order = new OrderInfo();
            // 订单类型
            int orderType = OrderTypeEnum.Shangou.getValue();
            order.setOrderType(orderType);
            // 卖家
            order.setSellerId(sellerId);
            String leaveWord = "autotest";
            order.setLeaveWord(leaveWord);
            // 运费
            BigDecimal freight = new BigDecimal(23);
            order.setFreight(freight);
            // 优惠券
            // 领用优惠券
            BigDecimal couponValue = new BigDecimal(10);
            // 领用商家优惠券
            String couponCode = new CouponCallService().receiveCouponInfo(sellerId, userId, couponValue);
            order.setCouponCode(couponCode);
            // 优惠券类型
            int couponType = 1;
            order.setCouponUseType(couponType);
            // 优惠券渠道
            int couponChannel = 2;
            order.setCouponChannel(couponChannel);
            // 优惠券金额
            order.setCouponValue(couponValue);
            // 是否全额付款
            boolean isPaidFull = false;
            order.setIsPaidFull(isPaidFull);
            // 收货地址
            String address = "上海市闸北区灵石路636号";
            order.setAddress(address);
            // 邮编
            String postCode = "200001";
            order.setPostCode(postCode);
            // 收件人姓名
            String receieveName = "李四";
            order.setReceieveName(receieveName);
            // 收货人手机号
            String phone = "13100000001";
            order.setPhone(phone);
            // 收货人电话
            String telephone = "021-51002100";
            order.setTelephone(telephone);
            // 自动取消小时数
            BigDecimal autoCancelOrderHours = new BigDecimal(10);
            order.setAutoCancelOrderHours(autoCancelOrderHours);
            // 订单商品信息
            List<OrderProductInfo> orderProductInfoList = new ArrayList<OrderProductInfo>();
            OrderProductInfo productinfo = new OrderProductInfo();
            OrderProductInfo productinfo2 = new OrderProductInfo();
            OrderProductInfo productinfo3 = new OrderProductInfo();
            // 商品id
            productinfo.setProductId(productId);
            // 商品名称
            productinfo.setProductName(productName);
            // 商品规格id
            String catalogId = TestDataManager.getRandomUUID().toString();
            productinfo.setCatalogId(catalogId);
            // 备货状态(1-现货 2-代购 3-FBX)
            int catalogType = StockStatusEnum.Spot.getValue();
            productinfo.setStockStatusEnum(catalogType);
            // 商品数量
            int productNum = 1 + new Random().nextInt(5);
            productinfo.setProductNum(productNum);
            // 商品一级目录id
            int firstCategoryId = 1;
            productinfo.setFirstCategoryId(firstCategoryId);
            // 商品一级目录id
            int secondCategoryId = 2;
            productinfo.setSecondCategoryId(secondCategoryId);
            // 商品一级目录id
            int thirdCategoryId = 3;
            productinfo.setThirdCategoryId(thirdCategoryId);
            // 商品品牌id
            int brandId = 5;
            productinfo.setBrandId(brandId);
            // 商品url
            productinfo.setPictureUrl(pic);
            // 商品属性信息(按JSON格式存储，如--颜色:黑色,尺寸:XXS)
            String propetyInfo = "";
            productinfo.setPropetyInfo(propetyInfo);
            // 商品价格
            BigDecimal productPrice = new BigDecimal(110);
            productinfo.setProductPrice(productPrice);
            // 商品预付定金价格
            BigDecimal earnestPrice = new BigDecimal(26); // 小数点后保留2位并四舍五入
            productinfo.setEarnestPrice(earnestPrice);
            // 价格类型
            int priceType = PriceTypeEnum.Unkown.getValue();
            productinfo.setPriceType(priceType);
            // 买家或卖家承担关税(0-卖家承担 1-买家承担)
            int tariffType = 0;
            productinfo.setTariffType(tariffType);
            // 物流类型
            int logisticsType = LogisticsTypeEnum.SailProtect.getValue();
            productinfo.setLogisticsType(logisticsType);
            // 保税区
            int bondedArea = BondedAreaEnum.NingBo.getValue();
            productinfo.setBondedArea(bondedArea);
            // 商品备案号
            String productRecordNo = "123456";
            productinfo.setProductRecordNo(productRecordNo);
            // SKU
            String sku = "1234567";
            productinfo.setSKU(sku);
            // 套餐编号
            String packageNo = "11111111";
            productinfo.setPackageNo(packageNo);
            // 商品退货渠道
            int productRefundChannel = ProductRefundChannelEnum.Official.getValue();
            productinfo.setProductRefundChannel(productRefundChannel);
            // 商品信息(存储格式为：Json格式)
            String productDetailInfo =
                    "e5a1eccf-6a14-458f-b907-35dc9a3d2713#适用人群:b13e9eb1-98d6-4d39-8c35-225758e443d3#男";
            productinfo.setProductDetailInfo(productDetailInfo);
            // 活动商品信息
            ProductActivityInfo activityInfo = new ProductActivityInfo();
            // 商品活动号
            int activityId = 46870;
            activityInfo.setActivityId(activityId);
            // 额外费用
            BigDecimal premium = new BigDecimal(10);
            activityInfo.setPremium(premium);
            // 是否算入成本价
            boolean isCost = false;
            activityInfo.setIsCost(isCost);
            // 是否使用优惠券
            boolean isUseCoupon = false;
            activityInfo.setIsUseCoupon(isUseCoupon);
            // 是否免佣金
            boolean isFeeFree = false;
            activityInfo.setIsFeeFree(isFeeFree);
            // 活动开始时间
            String beginDate = YMTDateUtil.getBeforeOrNextDay(-100);
            activityInfo.setActivityBeginDate(beginDate);
            // 活动结束时间
            String endDate = YMTDateUtil.getBeforeOrNextDay(10);
            activityInfo.setActivityEndDate(endDate);
            // 商品活动模板号
            int activityTemplateId = 987654;
            activityInfo.setActivityTemplateId(activityTemplateId);
            // 商品活动促销类型
            int promotionType = ActivityPromotionTypeEnum.DiscountPrice.getValue();
            activityInfo.setPromotionType(promotionType);
            // 促销价格
            BigDecimal promotionPrice = new BigDecimal(1);
            activityInfo.setPromotionPrice(promotionPrice);
            // 促销价格
            BigDecimal commissionRate = new BigDecimal(0);
            activityInfo.setCommissionRate(commissionRate);
            productinfo.setActivityInfo(activityInfo);
            // 第二件商品
            // 商品id
            productinfo2.setProductId(productId);
            // 商品名称
            productinfo2.setProductName(productName);
            // 商品规格id
            String catalogId2 = TestDataManager.getRandomUUID().toString();
            productinfo2.setCatalogId(catalogId2);
            // 备货状态(1-现货 2-代购 3-FBX)
            int catalogType2 = StockStatusEnum.Spot.getValue();
            productinfo2.setStockStatusEnum(catalogType2);
            // 商品数量
            int productNum2 = 1 + new Random().nextInt(5);
            productinfo2.setProductNum(productNum2);
            // 商品一级目录id
            int firstCategoryId2 = 1;
            productinfo2.setFirstCategoryId(firstCategoryId2);
            // 商品一级目录id
            int secondCategoryId2 = 2;
            productinfo2.setSecondCategoryId(secondCategoryId2);
            // 商品一级目录id
            int thirdCategoryId2 = 3;
            productinfo2.setThirdCategoryId(thirdCategoryId2);
            // 商品品牌id
            int brandId2 = 3;
            productinfo2.setBrandId(brandId2);
            // 商品url
            productinfo2.setPictureUrl(pic);
            // 商品属性信息(按JSON格式存储，如--颜色:黑色,尺寸:XXS)
            String propetyInfo2 = "";
            productinfo2.setPropetyInfo(propetyInfo2);
            // 商品价格
            BigDecimal productPrice2 = new BigDecimal(126);
            productinfo2.setProductPrice(productPrice2);
            // 商品预付定金价格
            BigDecimal earnestPrice2 = new BigDecimal(35); // 小数点后保留2位并四舍五入
            productinfo2.setEarnestPrice(earnestPrice2);
            // 价格类型
            int priceType2 = PriceTypeEnum.NewPersonPrice.getValue();
            productinfo2.setPriceType(priceType2);
            // 买家或卖家承担关税(0-卖家承担 1-买家承担)
            int tariffType2 = 0;
            productinfo2.setTariffType(tariffType2);
            // 物流类型
            int logisticsType2 = LogisticsTypeEnum.XloboBondedDelivery.getValue();
            productinfo2.setLogisticsType(logisticsType2);
            // 保税区
            int bondedArea2 = BondedAreaEnum.NingBo.getValue();
            productinfo2.setBondedArea(bondedArea2);
            // 商品备案号
            String productRecordNo2 = "123456";
            productinfo2.setProductRecordNo(productRecordNo2);
            // SKU
            String sku2 = "1234567";
            productinfo2.setSKU(sku2);
            // 套餐编号
            String packageNo2 = "11111111";
            productinfo2.setPackageNo(packageNo2);
            // 商品退货渠道
            int productRefundChannel2 = ProductRefundChannelEnum.Official.getValue();
            productinfo2.setProductRefundChannel(productRefundChannel2);
            // 商品信息(存储格式为：Json格式)
            String productDetailInfo2 =
                    "e5a1eccf-6a14-458f-b907-35dc9a3d2713#适用人群:b13e9eb1-98d6-4d39-8c35-225758e443d3#男";
            productinfo2.setProductDetailInfo(productDetailInfo2);
            productinfo2.setActivityInfo(activityInfo);
            // 第三件商品
            // 商品id
            productinfo3.setProductId(productId);
            // 商品名称
            productinfo3.setProductName(productName);
            // 商品规格id
            String catalogId3 = TestDataManager.getRandomUUID().toString();
            productinfo3.setCatalogId(catalogId3);
            // 备货状态(1-现货 2-代购 3-FBX)
            productinfo3.setStockStatusEnum(catalogType);
            // 商品数量
            int productNum3 = 1 + new Random().nextInt(5);
            productinfo3.setProductNum(productNum3);
            // 商品一级目录id
            productinfo3.setFirstCategoryId(firstCategoryId);
            // 商品一级目录id
            productinfo3.setSecondCategoryId(secondCategoryId);
            // 商品一级目录id
            productinfo3.setThirdCategoryId(thirdCategoryId);
            // 商品品牌id
            int brandId3 = 3;
            productinfo3.setBrandId(brandId3);
            // 商品url
            productinfo3.setPictureUrl(pic);
            // 商品属性信息(按JSON格式存储，如--颜色:黑色,尺寸:XXS)
            String propetyInfo3 = "";
            productinfo3.setPropetyInfo(propetyInfo3);
            // 商品价格
            BigDecimal productPrice3 = price;
            productinfo3.setProductPrice(productPrice3);
            // 商品预付定金价格
            BigDecimal earnestPrice3 = price.divide(new BigDecimal(3), 2, BigDecimal.ROUND_HALF_UP); // 小数点后保留2位并四舍五入
            productinfo3.setEarnestPrice(earnestPrice3);
            // 价格类型
            int priceType3 = PriceTypeEnum.NewPersonPrice.getValue();
            productinfo3.setPriceType(priceType3);
            // 买家或卖家承担关税(0-卖家承担 1-买家承担)
            int tariffType3 = 0;
            productinfo3.setTariffType(tariffType3);
            // 物流类型
            int logisticsType3 = LogisticsTypeEnum.XloboBondedDelivery.getValue();
            productinfo3.setLogisticsType(logisticsType3);
            // 保税区
            int bondedArea3 = BondedAreaEnum.NingBo.getValue();
            productinfo3.setBondedArea(bondedArea3);
            // 商品备案号
            productinfo3.setProductRecordNo(productRecordNo);
            // SKU
            productinfo3.setSKU(sku);
            // 套餐编号
            productinfo3.setPackageNo(packageNo);
            // 商品退货渠道
            productinfo3.setProductRefundChannel(productRefundChannel);
            // 商品信息(存储格式为：Json格式)
            productinfo3.setProductDetailInfo(productDetailInfo);
            // 活动商品信息
            productinfo3.setActivityInfo(activityInfo);

            orderProductInfoList.add(productinfo);
            orderProductInfoList.add(productinfo2);
            orderProductInfoList.add(productinfo3);
            // 订单商品信息
            order.setOrderProductInfoList(orderProductInfoList);
            // 第二个订单
            OrderInfo order2 = new OrderInfo();
            // 订单类型
            int orderType2 = OrderTypeEnum.Shangou.getValue();
            order2.setOrderType(orderType2);
            // 卖家
            order2.setSellerId(sellerId);
            String leaveWord2 = "autotest";
            order2.setLeaveWord(leaveWord2);
            // 运费
            BigDecimal freight2 = new BigDecimal(20);
            order2.setFreight(freight2);
            // 优惠券
            BigDecimal couponValue2 = new BigDecimal(11);
            // ymt 平台优惠券
            String couponCode2 = new OrderCallService().receivePlatformCoupon(userId, couponValue);
            order2.setCouponCode(couponCode2);
            // 优惠券类型
            int couponType2 = 1;
            order2.setCouponUseType(couponType2);
            // 优惠券渠道 1 ymt平台，2 商家
            int couponChannel2 = 1;
            order2.setCouponChannel(couponChannel2);
            // 优惠券金额
            order2.setCouponValue(couponValue2);
            // 是否全额付款
            boolean isPaidFull2 = false;
            order2.setIsPaidFull(isPaidFull2);
            // 收货地址
            String address2 = "上海市闸北区灵石路636号";
            order2.setAddress(address2);
            // 邮编
            String postCode2 = "200001";
            order2.setPostCode(postCode2);
            // 收件人姓名
            String receieveName2 = "李四";
            order2.setReceieveName(receieveName2);
            // 收货人手机号
            String phone2 = "13100000002";
            order2.setPhone(phone2);
            // 收货人电话
            String telephone2 = "021-51002111";
            order2.setTelephone(telephone2);
            // 自动取消小时数
            BigDecimal autoCancelOrderHours2 = new BigDecimal(2);
            order2.setAutoCancelOrderHours(autoCancelOrderHours2);
            // 订单商品信息 拷贝第一单3个商品
            order2.setOrderProductInfoList(orderProductInfoList);
            // 订单信息
            orderInfoList.add(order);
            // 订单信息
            orderInfoList.add(order2);
            placeorderBean.setUserId(userId);
            placeorderBean.setOrderInfoList(orderInfoList);
            placeorderCall.setData(placeorderBean);
            placeorderCall.callService();
            JSONArray orders = placeorderCall.getOrderIds();
            int tradingId = placeorderCall.getTradingId();
            map.put("orders", orders);
            map.put("tradingId", tradingId);
        } catch (Exception e) {
            Logger.fail(e);
        }
        return map;
    }


}
